package com.mall.common.config.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;


/**
 * zk客户端
 *
 * @author: xrj
 * @date: 2022/5/1 2:02
 * @description:
 */

public class CuratorFrameworkClient {

    ZooKeeperClient zooKeeperClient;

    CuratorFramework curatorFramework = null;

    public CuratorFrameworkClient() {
    }

    public CuratorFrameworkClient(ZooKeeperClient zooKeeperClient) {
        this.zooKeeperClient = zooKeeperClient;
    }

    public CuratorFramework getZkClient() {
        if (curatorFramework == null) {
            return createCuratorFramework();
        } else {
            if (zooKeeperClient.isSingleton()) {
                return curatorFramework;
            } else {
                return createCuratorFramework();
            }
        }
    }

    public CuratorFramework createCuratorFramework() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 100, 2000);
        curatorFramework = (CuratorFramework) CuratorFrameworkFactory.builder().
                connectString(zooKeeperClient.getZkHosts()).
                sessionTimeoutMs(zooKeeperClient.getSessionTimeout()).
                namespace(zooKeeperClient.getNamespace()).
                retryPolicy(retryPolicy);
        curatorFramework.start();
        return curatorFramework;
    }
}
